package com.bobo.netty.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.GsonBuilder;
import lombok.SneakyThrows;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class JsonUtils {
    static GsonBuilder gb = new GsonBuilder();
    static {
        gb.disableHtmlEscaping();
    }

    /**
     * Java对象转json
     * @param obj
     * @return
     */
    public static String pojoToJson(Object obj){
        return gb.create().toJson(obj);
    }

    /**
     * json对象转POJO
     * @param json
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T>T jsonToPojo(String json,Class<T> tClass){
        try {
            return JSONObject.parseObject(json,tClass);
        }catch (Exception e){
            return null;
        }
    }

    @SneakyThrows
    public <T> Map<String, Object> convert2Map(Object obj) {
        Map<String, Object> map = new HashMap<String, Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            if (value != null) {
                map.put(fieldName, value);
            }
        }
        return map;
    }
}
